package user

import (
	"context"
	"github.com/pkg/errors"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRoleBindLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRoleBindLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRoleBindLogic {
	return &UserRoleBindLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRoleBindLogic) UserRoleBind(req *types.UserRoleBindRo) (resp *types.BaseRsp, err error) {
	for _, v := range req.RoleIds {
		if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", v).First(&model.RoleConfig{}).Error; err != nil {
			return nil, errors.Wrap(err, "角色不存在")
		}
	}

	var roleSplitStr model.IntSplitStr
	roleSplitStr = roleSplitStr.Marshal(req.RoleIds)

	err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.User{}).Where("Id=?", req.Uid).
		Update("Roles", roleSplitStr).Error

	return
}
